<?php


namespace App\Traits;

use App\Enums\ResponseCode;
use App\Exceptions\BusinessException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\App;
use JetBrains\PhpStorm\NoReturn;


trait ApiResponse
{
    /**
     * 成功
     * @param $message
     * @param int $code
     * @param null $data
     * @param null $error
     * @return JsonResponse
     */
    public static function success($message, int $code=ResponseCode::OK,$data = null, $error=null): JsonResponse
    {
        return self::jsonResponse('success', $code,$message, $data, $error);
    }

    /**
     * 失败
     * @param int $code
     * @param string $message
     * @param null $data
     * @param null $error
     * @return JsonResponse
     */
    public function fail(string $message,int $code = ResponseCode::BAD_GATEWAY, $data = null, $error=null): JsonResponse
    {
        return self::jsonResponse('fail', $code,$message, $data, $error);
    }
    /**
     * 失败
     * @param int $code
     * @param string $message
     * @param null $data
     * @param null $error
     * @return JsonResponse
     */
    public function error(string $message,int $code =  ResponseCode::BAD_REQUEST, $data = null, $error=null): JsonResponse
    {
        return self::jsonResponse('error', $code, $message, $data, $error);
    }

    /**
     * json响应
     * @param $status
     * @param $code
     * @param $message
     * @param $data
     * @param $error
     * @return JsonResponse
     */
    #[NoReturn] private static function jsonResponse($status, $code, $message, $data, $error): JsonResponse
    {
        return response()->json([
            'status'  => $status,
            'code'    => $code,
            'local' =>  App::getLocale(),
            'message' => $message,
            'data'    => $data ?: new \stdClass(),
            'error'  => $error ?: new \stdClass(),
        ]);
    }

    /**
     * 抛出异常。
     *
     * @param int $errCode 错误编号。
     * @param string $errMsg 错误信息。
     * @throws BusinessException
     */
    public static function exception(int $errCode ,string $errMsg)
    {

        throw new BusinessException($errMsg, $errCode);
    }
}
